package cn.iocoder.yudao.module.system.framework.sms.core.client.impl;

import cn.hutool.core.lang.Assert;
import cn.hutool.json.JSONUtil;
import cn.iocoder.yudao.framework.common.core.KeyValue;
import cn.iocoder.yudao.module.system.framework.sms.core.client.dto.SmsReceiveRespDTO;
import cn.iocoder.yudao.module.system.framework.sms.core.client.dto.SmsSendRespDTO;
import cn.iocoder.yudao.module.system.framework.sms.core.client.dto.SmsTemplateRespDTO;
import cn.iocoder.yudao.module.system.framework.sms.core.client.pojo.SendReq;
import cn.iocoder.yudao.module.system.framework.sms.core.property.SmsChannelProperties;
import cn.iocoder.yudao.module.system.util.MD5Util;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
public class SMSYDClient  extends AbstractSmsClient{
    private static Gson gson;
    static {
        GsonBuilder gb = new GsonBuilder();
        gb.setDateFormat("yyyy-MM-dd HH:mm:ss");
        gson = gb.create();
    }
    public SMSYDClient(SmsChannelProperties properties) {


        super(properties);
        log.info("SmsChannelProperties======>"+JSON.toJSONString(properties));
        Assert.notEmpty(properties.getApiKey(), "apiKey 不能为空");
        Assert.notEmpty(properties.getApiSecret(), "apiSecret 不能为空");
    }

    @Override
    public SmsSendRespDTO sendSms(Long logId, String mobile, String apiTemplateId, List<KeyValue<String, Object>> templateParams) throws Throwable {
        SmsSendRespDTO smsSendRespDTO = new SmsSendRespDTO();
        String content;//消息的内容
        log.info("===================>"+logId);
        log.info("==================>mobile"+mobile);
        log.info("=================>apiTemplateId"+apiTemplateId);
        log.info("=================>templateParams"+ templateParams.get(0).getValue());
        //构建请求
        content = templateParams.get(0).getValue().toString();
        SendReq  sendReq = new SendReq();
        sendReq.setApId(properties.getApiKey());
        sendReq.setEcName("杭州市第三人民医院");
        sendReq.setSecretKey(properties.getApiSecret());
        sendReq.setContent(content); //短信内容
        sendReq.setMobiles(mobile);//手机号码
        sendReq.setAddSerial("");
        sendReq.setSign("iHMYCk1dN");

        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append(sendReq.getEcName());
        stringBuffer.append(sendReq.getApId());
        stringBuffer.append(sendReq.getSecretKey());
        stringBuffer.append(sendReq.getMobiles());
        stringBuffer.append(sendReq.getContent());
        stringBuffer.append(sendReq.getSign());
        stringBuffer.append(sendReq.getAddSerial());
        log.info("stringBuffer:" + stringBuffer);
        sendReq.setMac(MD5Util.MD5(stringBuffer.toString()).toLowerCase());
        String reqText = gson.toJson(sendReq);
        log.info("JSON===>"+reqText);
        String encode = Base64.encodeBase64String(reqText.getBytes("UTF-8"));
        log.info("encode:"+encode);
        log.info("开始执行短信发送===================>");
        String resStr = sendPost("http://112.35.1.155:1992/sms/norsubmit",encode);
        log.info("resStr::"+resStr);
        JSONObject json = JSONObject.parseObject(resStr);
        if (json!=null){
            String rspcod = json.getString("rspcod").toString();
            if (!rspcod.isEmpty() && rspcod.equalsIgnoreCase("success")){
                boolean  success = json.getBooleanValue("success");
                String msgGroup = json.getString("msgGroup").toString();
                smsSendRespDTO.setSuccess(success);
                smsSendRespDTO.setSerialNo(msgGroup);
            }

        }
        return smsSendRespDTO;
    }
    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url   发送请求的 URL
     * @param param 请求参数
     * @return 所代表远程资源的响应结果
     */
    private String sendPost(String s, String encode) {
        OutputStreamWriter out = null;

        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(s);
            URLConnection conn = realUrl.openConnection();
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("contentType", "utf-8");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
            conn.setDoOutput(true);
            conn.setDoInput(true);

            out = new OutputStreamWriter(conn.getOutputStream());
            out.write(encode);
            out.flush();

            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += "\n" + line;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result;

    }

    @Override
    public List<SmsReceiveRespDTO> parseSmsReceiveStatus(String text) throws Throwable {
        return null;
    }

    @Override
    public SmsTemplateRespDTO getSmsTemplate(String apiTemplateId) throws Throwable {
        return null;
    }

    @Override
    protected void doInit() {

    }
}
